package com.zbl.zblproject.core.service.impl;


import com.alibaba.fastjson.JSONArray;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.*;
import com.zbl.zblproject.core.service.OrderService;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.core.utils.TimeUtil;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.mapper.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/16
 */
@Service
public class OrderServiceImpl implements OrderService {


    @Value("${remote-url}")
    private String remoteUrl;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private ErpCategoryMapper categoryMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private AdminUserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Autowired
    private ErpWarehouseItemMapper warehouseItemMapper;

    @Autowired
    private ErpWarehouseMapper erpWarehouseMapper;

    @Autowired
    private SmallUnitMapper smallUnitMapper;

    @Autowired
    private ErpTempOrderItemMapper erpTempOrderItemMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpGoodMapper goodMapper;

    @Autowired
    private SmallUnitMapper unitMapper;

    @Autowired
    private ErpFinanceLogMapper erpFinanceLogMapper;

    @Autowired
    private ErpOweGoodsItemMapper erpOweGoodsItemMapper;

    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;


    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);


    @Override
    public List<InvoiceOrder> getInvoiceOrderById(int userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Order> orders = orderMapper.selectList(wrapper);
        //查询用户下所有的订单
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());
        List<ErpTempOrderItem> items = erpTempOrderItemMapper.listByOrderSn(orderSn);

        Map<Integer, InvoiceOrder> map = new HashMap<>();
        InvoiceOrder invoiceOrder;
        for (ErpTempOrderItem item : items) {
            //Map里不能存在重复出现的Item

            invoiceOrder = new InvoiceOrder(item.cloneNew());
            map.put(item.getGoodsId(), invoiceOrder);

            //仓库数据及排序处理
            List<ErpWarehouseItem> warehouseItems = warehouseItemMapper.selectItemByGoodsId(item.getGoodsId());
            warehouseItems.forEach(x -> {
                x.setErpWarehouse(erpWarehouseMapper.selectById(x.getWhId()));
            });
            invoiceOrder.setItems(warehouseItems);
        }

        List<InvoiceOrder> coll =
                map.values().stream().collect(Collectors.toList());

        coll.forEach(x -> {
            ErpTempOrderItem goods = x.getGoods();
            ErpGoods tempGoods = goodMapper.selectById(goods.getGoodsId());
            if (tempGoods != null) {
                goods.setSupplier(supplierMapper.selectById(tempGoods.getSuppliersId()));
                goods.setBrandName(brandMapper.selectById(tempGoods.getBrandId()).getBrandName());
                SmallUnit unit = unitMapper.selectById(tempGoods.getSmallunitId());
                if (unit == null) {
                    goods.setGoodsUnit("件");
                } else {
                    goods.setGoodsUnit(unit.getName());
                }
            }
        });

        return coll;
    }

    @Override
    public List<InvoiceOrder> getInvoiceOrderByIdforWh(int userId) {

        List<InvoiceOrder> coll = getInvoiceOrderById(userId);
        coll.forEach(x -> {
            Collections.sort(x.getItems(), (x1, x2) -> {
                return x1.getErpWarehouse().getGoodsAllocation().compareTo(x2.getErpWarehouse().getGoodsAllocation());
            });
        });
        return coll;
    }

    @Override
    public boolean updateOrderContext(String orderSn, String context) {
        return orderMapper.updateOrderContext(orderSn, context);
    }

    @Override
    public boolean updateOrderConfirm(String orderSn, int status, int userId) {
        Order order = orderMapper.selectByOrderSn(orderSn);
        if(order == null){
            return false;
        }
        //CGDD订单确认
        ErpFinanceLog log = erpFinanceLogMapper.selectLogByOrderSn(orderSn);
        if(log == null) {
            log = new ErpFinanceLog();
            log.setOrderNumber("FK" + Instant.now().toEpochMilli());
            log.setOrderSn(orderSn);
            log.setChecktime(LocalDateTime.now());
            // 付款金额
            log.setTotal(orderItemMapper.selectOrderTotal(orderSn));
            log.setStatus(ErpOrderStatus.submit.getStatus());
            //工厂名称
            log.setStoreName(orderMapper.selectSupplierNameByOrderSn(orderSn));
            Supplier supplier = supplierMapper.selectSupplierByName(log.getStoreName());
            if(supplier == null){
                throw new RuntimeException("供应商不存在!");
            }
            log.setUserBalance(supplier.getBalance());
            log.setMode(ErpFinanceLog.MODE_PAYMENT);
            BigDecimal rebateRate = supplier.getRebateRate();
            if(rebateRate == null || rebateRate.doubleValue() == 0.0){
                rebateRate = BigDecimal.ZERO;
            }
            log.setRebateRate(rebateRate);
            BigDecimal rebate = log.getSubTotal().multiply(log.getRebateRate());
            log.setRebate(rebate);
            log.setCreater(adminUserMapper.selectNameById(userId));
            erpFinanceLogMapper.insert(log);
            return orderMapper.updateOrderConfirm(orderSn, status);
        }else{
            Supplier supplier = supplierMapper.selectSupplierByName(log.getStoreName());
            if(supplier == null){
                throw new RuntimeException("供应商不存在!");
            }
            log.setTotal(orderItemMapper.selectOrderTotal(orderSn));
            log.setStatus(ErpOrderStatus.submit.getStatus());
            log.setUserBalance(supplier.getBalance());
            BigDecimal rebateRate = supplier.getRebateRate();
            if(rebateRate == null || rebateRate.doubleValue() == 0.0){
                rebateRate = BigDecimal.ZERO;
            }
            log.setRebateRate(rebateRate);
            BigDecimal rebate = log.getTotal().multiply(log.getRebateRate());
            log.setRebate(rebate);
            erpFinanceLogMapper.updateById(log);
            return orderMapper.updateOrderConfirm(orderSn, status);
        }
    }

    @Override
    public Order updateOrder(String orderNo, int operatorId, int userId, int addressId, int isPay, int warehouse, int isPur, int isNopur, List<ErpTempOrderItem> list) {
        AdminUser user = userMapper.selectById(userId);
        Preconditions.checkNotNull(user, "用户不存在");
        if (user.getStatus() != 0) {
            throw new RuntimeException("门店状态未启用");
        }
        Order order = orderMapper.selectByOrderSn(orderNo);
        order.setUserId(user.getUserId());
        order.setOperatorId(operatorId);
        order.setAddressId(String.valueOf(addressId));
        order.setIsPay(isPay);
        order.setWarehouseConfirm(warehouse);
        BigDecimal price = new BigDecimal(0);


        OrderItem orderItem;
        ErpGoods goods;

        orderItemMapper.deleteOrderSn(order.getOrderSn());

        //记录下所有的orderItemId
        if (isNopur == 1) {
            List<Integer> ids = list.stream().map(ErpTempOrderItem::getOrderItemId).filter(x -> x > 0).collect(Collectors.toList());

            if (!ids.isEmpty()) {
                orderItemMapper.updateItemsNopurByIds(ids);
            }
        }

        //将list根据goodsId来合并
        List<ErpTempOrderItem> items = new ArrayList<>();
        list.stream().collect(Collectors.groupingBy(ErpTempOrderItem::getGoodsId))
                .forEach((k, v) -> {
                    Optional<ErpTempOrderItem> item = v.stream().reduce((v1, v2) -> {
                        v1.setGoodsNum(v1.getGoodsNum() + v2.getGoodsNum());
                        return v1;
                    });
                    items.add(item.get());
                });

        for (ErpTempOrderItem item : items) {
            orderItem = new OrderItem();
            goods = goodMapper.selectById(item.getGoodsId());
            orderItem.setBrandName(item.getBrandName());
            orderItem.setCartsId(goods.getCatId());
            orderItem.setGoodsId(item.getGoodsId());
            orderItem.setGoodsNum(item.getGoodsNum());
            orderItem.setShopPrice(goods.getShopPrice());
            orderItem.setOrderSn(order.getOrderSn());
            orderItem.setGoodsDesc(item.getSpecifications());
            orderItem.setGoodsName(item.getGoodsName());
            orderItem.setIsPurchasing(isPur);
            Integer suppliersId = Optional.ofNullable(supplierMapper.selectSupplierIdByGoodsId(item.getGoodsId())).orElse(0);
            orderItem.setSuppliersId(suppliersId);
            //技术总价
            price = price.add(goods.getShopPrice().multiply(new BigDecimal(item.getGoodsNum())));

            orderItemMapper.insert(orderItem);
        }
        order.setTotalMoney(price.doubleValue());
        orderMapper.updateById(order);
        return order;
    }

    @Override
    public Order createOrder(String orderNo, int operatorId, int userId, int addressId, int isPay, int warehouse, int isPur, int isNopur, List<ErpTempOrderItem> list, String context) {
        AdminUser user = userMapper.selectById(userId);
        Preconditions.checkNotNull(user, "用户不存在");
        if (user.getStatus() != 0) {
            throw new RuntimeException("门店状态未启用");
        }

        // 判断订单是否存在，如果存在报错，订单已经存在
        if (orderMapper.checkIsExist(orderNo) != 0) {
            throw new RuntimeException("订单号已经存在");
        }

        Order order = new Order();
        order.setCreateTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        order.setUserId(user.getUserId());
        order.setOperatorId(operatorId);
        order.setAddressId(String.valueOf(addressId));
        order.setOrderSn(orderNo);
        order.setIsPay(isPay);
        order.setWarehouseConfirm(warehouse);
        order.setContext(context);

        BigDecimal price = new BigDecimal(0);


        OrderItem orderItem;
        ErpGoods goods;

        //记录下所有的orderItemId
        if (isNopur == 1) {
            List<Integer> ids = list.stream().map(ErpTempOrderItem::getOrderItemId).filter(x -> x > 0).collect(Collectors.toList());

            if (!ids.isEmpty()) {
                orderItemMapper.updateItemsNopurByIds(ids);
            }
        }

        //将list根据goodsId来合并
        List<ErpTempOrderItem> items = new ArrayList<>();


        list.stream().collect(Collectors.groupingBy(ErpTempOrderItem::getGoodsId))
                .forEach((k, v) -> {
                    Optional<ErpTempOrderItem> item = v.stream().reduce((v1, v2) -> {
                        v1.setGoodsNum(v1.getGoodsNum() + v2.getGoodsNum());
                        return v1;
                    });
                    items.add(item.get());
                });

        for (ErpTempOrderItem item : items) {
            orderItem = new OrderItem();
            goods = goodMapper.selectById(item.getGoodsId());
            orderItem.setBrandName(item.getBrandName());
            orderItem.setCartsId(goods.getCatId());
            orderItem.setGoodsId(item.getGoodsId());
            orderItem.setGoodsNum(item.getGoodsNum());
            orderItem.setShopPrice(goods.getShopPrice());
            orderItem.setOrderSn(order.getOrderSn());
            orderItem.setGoodsDesc(item.getSpecifications());
            orderItem.setGoodsName(item.getGoodsName());
            orderItem.setIsPurchasing(isPur);
            Integer suppliersId = Optional.ofNullable(supplierMapper.selectSupplierIdByGoodsId(item.getGoodsId())).orElse(0);
            orderItem.setSuppliersId(suppliersId);
            //技术总价
            price = price.add(goods.getShopPrice().multiply(new BigDecimal(item.getGoodsNum())));

            orderItemMapper.insert(orderItem);
        }
        order.setTotalMoney(price.doubleValue());
        orderMapper.insert(order);
        return order;
    }

    @Override
    public List<FactoryOrder> getSupplierOrderListForOrderSn(int mode, String start, String end, String name, String orderNo) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("is_pay", 1).eq("is_cancel", "0");
        if (mode == 0) {
            wrapper.likeRight("order_sn", "CGDD");
        } else {
            wrapper.notLike("order_sn", "CGDD");
        }
        //订单号查询
        if (!StringUtil.isNullOrEmpty(orderNo)) {
            wrapper.like("order_sn", orderNo.trim());
        }


        //订单时间查询
        if (!StringUtil.isNullOrEmpty(start.trim()) && !StringUtil.isNullOrEmpty(end.trim())) {
            long startTime = TimeUtil.parseTimeToInstant(start);
            long endTime = TimeUtil.parseTimeToInstant(end);
            wrapper.between("create_time", startTime, endTime);
        }


        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(wrapper);
        //orders的订单号

        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());

        if (orderSn.isEmpty()) {
            return null;
        }
        List<Integer> supplierIds = supplierMapper.selectSupplierIdByOrderSn(orderSn);
        // logger.info("工厂订单号数量:{} 工厂订单号:{} 供应商ID:{}", orders.size(), orderSn.toString(), supplierIds);
        List<Supplier> suppliers = supplierMapper.selectBatchIds(supplierIds);
        if (!StringUtil.isNullOrEmpty(name)) {
            suppliers = suppliers.stream().filter((x) -> {
                return x.getSuppliersName().contains(name);
            }).collect(Collectors.toList());
        }
        List<FactoryOrder> factoryOrders = loadSupplierByOrderSn(suppliers, orderSn, mode);

        return factoryOrders;
    }


    @Override
    public Result getSupplierOrderListForOrderSnByLimit(int mode, String start, String end, String name, String orderNo, int current, int size) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("is_pay", 1).eq("is_cancel", "0");
        if (mode == 0) {
            wrapper.likeRight("order_sn", "CGDD");
        } else {
            wrapper.notLike("order_sn", "CGDD");
        }
        //订单号查询
        if (!StringUtil.isNullOrEmpty(orderNo)) {
            wrapper.like("order_sn", orderNo.trim());
        }


        //订单时间查询
        if (!StringUtil.isNullOrEmpty(start.trim()) && !StringUtil.isNullOrEmpty(end.trim())) {
            long startTime = TimeUtil.parseTimeToInstant(start);
            long endTime = TimeUtil.parseTimeToInstant(end);
            wrapper.between("create_time", startTime, endTime);
        }


        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(wrapper);
        //orders的订单号

        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());

        if (orderSn.isEmpty()) {
            return null;
        }
        List<Integer> supplierIds = supplierMapper.selectSupplierIdByOrderSn(orderSn);
        //logger.info("工厂订单号数量:{} 工厂订单号:{} 供应商数量:{} 供应商ID:{}", orders.size(), orderSn.toString(), supplierIds.size(), supplierIds);
        List<Supplier> suppliers = supplierMapper.selectBatchIds(supplierIds);

        MiniPage page = null;

        if (!StringUtil.isNullOrEmpty(name)) {
            long supplierSize = suppliers.stream().filter((x) -> {
                return x.getSuppliersName().contains(name);
            }).count();
            page = new MiniPage((int) supplierSize, size, current);

            suppliers = suppliers.stream().filter((x) -> {
                return x.getSuppliersName().contains(name);
            }).skip((current - 1) * size).limit(size).collect(Collectors.toList());
        } else {
            int supplierSize = suppliers.size();
            page = new MiniPage(supplierSize, size, current);
            suppliers = suppliers.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList());
        }


        List<FactoryOrder> factoryOrders = loadSupplierByOrderSn(suppliers, orderSn, mode);

        if (factoryOrders == null) {
            return ResultUtil.error("没有FactoryOrder");
        }
        return ResultUtil.success("成功", factoryOrders).setAnother(page);
    }


    @Override
    public List<FactoryOrder> getSupplierOrder(int mode, String start, String end, String name, String orderNo) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("is_pay", 1).eq("is_cancel", "0");
        if (mode == 2) {
            //mode = 2:合并门店订单
            //   wrapper.eq("warehouse_confirm", "0");
        }
        if (mode == 0) {
            wrapper.likeRight("order_sn", "CGDD");
        } else {
            wrapper.notLike("order_sn", "CGDD");
        }
        //订单号查询
        if (!StringUtil.isNullOrEmpty(orderNo)) {
            wrapper.like("order_sn", orderNo.trim());
        }


        //订单时间查询
        if (!StringUtil.isNullOrEmpty(start.trim()) && !StringUtil.isNullOrEmpty(end.trim())) {
            long startTime = TimeUtil.parseTimeToInstant(start);
            long endTime = TimeUtil.parseTimeToInstant(end);
            wrapper.between("create_time", startTime, endTime);
        }


        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(wrapper);
        //orders的订单号

        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());

        if (orderSn.isEmpty()) {
            return null;
        }
        List<Integer> supplierIds = supplierMapper.selectSupplierIdByOrderSn(orderSn);
        //logger.info("工厂订单号数量:{} 工厂订单号:{} 供应商ID:{}", orders.size(), orderSn.toString(), supplierIds);
        List<Supplier> suppliers = supplierMapper.selectBatchIds(supplierIds);
        if (!StringUtil.isNullOrEmpty(name)) {
            suppliers = suppliers.stream().filter((x) -> {
                return x.getSuppliersName().contains(name);
            }).collect(Collectors.toList());
        }
        List<FactoryOrder> factoryOrders = loadSupplierByName(suppliers, orderSn, mode);
        return factoryOrders;
    }


    @Override
    public FactoryOrder getSupplierOrderByMode2(String name, String start, String end) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("suppliers_name", name);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("is_pay", 1).eq("is_cancel", 0).notLike("order_sn", "CGDD");
        //所有待查询的订单号
        if (!StringUtil.isNullOrEmpty(start.trim()) && !StringUtil.isNullOrEmpty(end.trim())) {
            long startTime = TimeUtil.parseTimeToInstant(start);
            long endTime = TimeUtil.parseTimeToInstant(end);
            orderWrapper.between("create_time", startTime, endTime);
        }
        List<Order> orders = orderMapper.selectList(orderWrapper);
        //orders的订单号
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());
        List<FactoryOrder> factoryOrders = loadSupplierByName(Arrays.asList(supplier), orderSn, 2);
        if (factoryOrders.isEmpty()) {
            return null;
        }
        return factoryOrders.get(0);
    }

    @Override
    public FactoryOrder getSupplierOrderByName(String name, String start, String end) {

        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("suppliers_name", name);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("is_pay", 1).eq("is_cancel", 0).likeRight("order_sn", "CGDD");
        if (!StringUtil.isNullOrEmpty(start.trim()) && !StringUtil.isNullOrEmpty(end.trim())) {
            long startTime = TimeUtil.parseTimeToInstant(start);
            long endTime = TimeUtil.parseTimeToInstant(end);
            orderWrapper.between("create_time", startTime, endTime);
        }

        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(orderWrapper);
        //orders的订单号
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());
        List<FactoryOrder> factoryOrders = loadSupplierByName(Arrays.asList(supplier), orderSn, 0);
        if (factoryOrders.isEmpty()) {
            return null;
        }
        return factoryOrders.get(0);
    }

    @Override
    public FactoryOrder getSupplierOrderByName(String name, String orderSn) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("suppliers_name", name);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        //orders的订单号
        List<FactoryOrder> factoryOrders = loadSupplierByName(Arrays.asList(supplier), Arrays.asList(orderSn), 0);
        if (factoryOrders.isEmpty()) {
            return null;
        }
        return factoryOrders.get(0);
    }

    @Override
    public FactoryOrder getSupplierOrderByNameNotCgdd(String name) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("suppliers_name", name);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("is_pay", 1).eq("is_cancel", "0").notLike("order_sn", "CGDD");
        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(orderWrapper);
        //orders的订单号
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());
        List<FactoryOrder> factoryOrders = loadSupplierByName(Arrays.asList(supplier), orderSn, 0);
        if (factoryOrders.isEmpty()) {
            return null;
        }
        return factoryOrders.get(0);
    }

    @Override
    public FactoryOrder getSupplierOrderByNameForDownloadFactoryExcel(String name, String start, String end) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("suppliers_name", name);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("is_pay", 1).eq("is_cancel", "0").notLike("order_sn", "CGDD");
        //所有待查询的订单号
        if (!StringUtil.isNullOrEmpty(start.trim()) && !StringUtil.isNullOrEmpty(end.trim())) {
            long startTime = TimeUtil.parseTimeToInstant(start);
            long endTime = TimeUtil.parseTimeToInstant(end);
            wrapper.between("create_time", startTime, endTime);
        }
        List<Order> orders = orderMapper.selectList(orderWrapper);
        //orders的订单号
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());
        List<FactoryOrder> factoryOrders = loadSupplierByOrderSn(Arrays.asList(supplier), orderSn, 2);
        if (factoryOrders.isEmpty()) {
            return null;
        }
        return factoryOrders.get(0);
    }

    @Override
    public FactoryOrder getSupplierOrderByNameForDownloadFactoryExcel(String name, String orderSn) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("suppliers_name", name);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        List<FactoryOrder> factoryOrders = loadSupplierByOrderSn(Arrays.asList(supplier), Arrays.asList(orderSn), 2);
        if (factoryOrders.isEmpty()) {
            return null;
        }
        return factoryOrders.get(0);
    }

    /**
     * Factory为工厂 工厂订单中为门店
     *
     * @param suppliers
     * @param orderSn
     * @param mode      查询orderitem 对 is_nopur进行判断  为1 is_nopur 必须等于0
     * @return
     */
    private List<FactoryOrder> loadSupplierByName(List<Supplier> suppliers, List<String> orderSn, int mode) {
        List<FactoryOrder> list = new ArrayList<>(suppliers.size());
        FactoryOrder factory;
        //所有的项目
        List<ErpTempOrderItem> allItem;
        //String为门店
        List<FactoryItem> userItem;
        for (Supplier supplier : suppliers) {
            factory = new FactoryOrder();
            factory.setSupplier(supplier);
            allItem = new ArrayList<>();
            userItem = new ArrayList<>();

            List<ErpTempOrderItem> items;
            if (mode == 0) {
                items = erpTempOrderItemMapper.listBySupIdAndOrderSn(orderSn, supplier.getSuppliersId());
            } else if (mode == 1) {
                items = erpTempOrderItemMapper.listBySupIdAndOrderSnIsPurZero(orderSn, supplier.getSuppliersId());
            } else if (mode == 2) {
                //未发起采购并且未出库
                items = erpTempOrderItemMapper.listBySupIdAndOrderSnByNoPurAndNoWare(orderSn, supplier.getSuppliersId());
            } else {
                items = erpTempOrderItemMapper.listBySupIdAndOrderSnAll(orderSn, supplier.getSuppliersId());
            }
            if (items.isEmpty()) {
                continue;
            }

            for (ErpTempOrderItem item : items) {

                //将数据插入所有项中
                if (allItem.contains(item)) {
                    ErpTempOrderItem orderItem = allItem.get(allItem.indexOf(item));
                    int goodsNum = item.getGoodsNum() + orderItem.getGoodsNum();
                    orderItem.setGoodsNum(goodsNum);

                } else {
                    allItem.add(item.cloneNew());
                }

                //门店
                AdminUser adminUser = adminUserMapper.selectById(item.getUserId());
                FactoryItem orderItems;

                //将所有数据插入到门店项中

                if (userItem.contains(new NameFactoryItem(adminUser.getUserName()))) {
                    orderItems = userItem.get(userItem.indexOf(new NameFactoryItem(adminUser.getUserName())));
                    if (orderItems.getItems().contains(item)) {
                        ErpTempOrderItem orderItem = orderItems.getItems().get(orderItems.getItems().indexOf(item));
                        orderItem.setGoodsNum(item.getGoodsNum() + orderItem.getGoodsNum());
                    } else {
                        orderItems.getItems().add(item.cloneNew());
                    }
                } else {
                    orderItems = new NameFactoryItem();
                    orderItems.setName(adminUser.getUserName());
                    orderItems.setItems(new ArrayList<>());
                    orderItems.getItems().add(item.cloneNew());
                    orderItems.setOrderSn(item.getOrderSn());
                    Order order = orderMapper.selectByOrderSn(item.getOrderSn());
                    if (order != null) {
                        orderItems.setContext(Optional.ofNullable(order.getContext()).orElse(""));

                    } else {
                        orderItems.setContext("");
                    }
                    userItem.add(orderItems);
                }
            }
            //数据插入
            factory.setAllItem(allItem);
            factory.setUserItem(userItem);

            list.add(factory);
        }
        return list;
    }


    private List<FactoryOrder> loadSupplierByOrderSn(List<Supplier> suppliers, List<String> orderSn, int mode) {

        List<FactoryOrder> list = new ArrayList<>(suppliers.size());
        FactoryOrder factory;
        //所有的项目
        List<ErpTempOrderItem> allItem;
        //String为门店
        List<FactoryItem> userItem;
        for (Supplier supplier : suppliers) {
            factory = new FactoryOrder();
            factory.setSupplier(supplier);
            allItem = new ArrayList<>();
            userItem = new ArrayList<>();

            //查询门店
            List<ErpTempOrderItem> items;
//            if(mode == 0) {
//                items = erpTempOrderItemMapper.listBySupIdAndOrderSn(orderSn, supplier.getSuppliersId());
//            }else{
//                items = erpTempOrderItemMapper.listBySupIdAndOrderSnIsPurZero(orderSn, supplier.getSuppliersId());
//            }
            if (mode == 0) {
                items = erpTempOrderItemMapper.listBySupIdAndOrderSn(orderSn, supplier.getSuppliersId());
            } else if (mode == 1) {
                items = erpTempOrderItemMapper.listBySupIdAndOrderSnIsPurZero(orderSn, supplier.getSuppliersId());
            } else if (mode == 2) {
                //未发起采购并且未出库
                items = erpTempOrderItemMapper.listBySupIdAndOrderSnByNoPurAndNoWare(orderSn, supplier.getSuppliersId());
            } else {
                items = erpTempOrderItemMapper.listBySupIdAndOrderSnAll(orderSn, supplier.getSuppliersId());
            }
            if (items.isEmpty()) {
                continue;
            }

            for (ErpTempOrderItem item : items) {

                //将数据插入所有项中
                if (allItem.contains(item)) {
                    ErpTempOrderItem orderItem = allItem.get(allItem.indexOf(item));
                    int goodsNum = item.getGoodsNum() + orderItem.getGoodsNum();
                    orderItem.setGoodsNum(goodsNum);
                } else {
                    allItem.add(item.cloneNew());
                }

                //门店
                AdminUser adminUser = adminUserMapper.selectById(item.getUserId());
                FactoryItem orderItems;

                //将所有数据插入到门店项中
                if (userItem.contains(new SnFactoryItem(item.getOrderSn()))) {
                    orderItems = userItem.get(userItem.indexOf(new SnFactoryItem(item.getOrderSn())));
                    if (orderItems.getItems().contains(item)) {
                        ErpTempOrderItem orderItem = orderItems.getItems().get(orderItems.getItems().indexOf(item));
                        orderItem.setGoodsNum(item.getGoodsNum() + orderItem.getGoodsNum());
                    } else {
                        orderItems.getItems().add(item.cloneNew());
                    }
                } else {
                    orderItems = new SnFactoryItem();
                    orderItems.setName(adminUser.getUserName());
                    orderItems.setItems(new ArrayList<>());
                    orderItems.getItems().add(item.cloneNew());
                    orderItems.setOrderSn(item.getOrderSn());
                    Order order = orderMapper.selectByOrderSn(item.getOrderSn());
                    if (order != null) {
                        orderItems.setContext(Optional.ofNullable(order.getContext()).orElse(""));
                        logger.info("订单号:{}  订单的confirm:{}", order.getOrderSn(), order.getIsConfirm());
                        ((SnFactoryItem) orderItems).setIsConfirm(order.getIsConfirm());
                    } else {
                        orderItems.setContext("");
                    }
                    Integer status = erpFinanceLogMapper.selectStatusByOrderSn(item.getOrderSn());
                    ((SnFactoryItem) orderItems).setFinanceLog(Optional.ofNullable(status).orElse(0));
                    userItem.add(orderItems);
                }
            }
            //数据插入
            factory.setAllItem(allItem);
            factory.setUserItem(userItem);

            list.add(factory);
        }
        return list;
    }


    @Override
    public List<ErpGoods> getGoodsByOrderSn(String orderSn) {
        List<ErpGoods> list = new ArrayList<>();

        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<OrderItem> items = orderItemMapper.selectList(wrapper);

        for (OrderItem item : items) {
            ErpGoods x = goodMapper.selectById(item.getGoodsId());
            x.setAllNum(x.getGoodsNumber());
            x.setGoodsNumber(item.getGoodsNum());
            x.setShopPrice(item.getShopPrice());
            x.setErpBrand(brandMapper.selectById(x.getBrandId()));
            x.setErpCategory(categoryMapper.selectById(x.getCatId()));
            x.setErpSupplier(supplierMapper.selectById(x.getSuppliersId()));
            SmallUnit smallUnit = smallUnitMapper.selectById(x.getSmallunitId());
            if (smallUnit == null) {
                x.setSmallUnitName("件");
            } else {
                x.setSmallUnitName(smallUnit.getName());
            }
            x.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId()));
            list.add(x);
        }

        return list;
    }


    @Override
    public List<UserFactoryOrder> getGoodsForOrderSnChildren(String orderSn) {
        List<UserFactoryOrder> list = new ArrayList<>();
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("po_sn", orderSn);
        List<Order> orders = orderMapper.selectList(wrapper);
        for (Order order : orders) {
            UserFactoryOrder factoryOrder = new UserFactoryOrder();
            factoryOrder.setGoods(getGoodsByOrderSn(order.getOrderSn()));
            factoryOrder.setOrderSn(order.getOrderSn());
            factoryOrder.setName(adminUserMapper.selectById(order.getUserId()).getUserName());
            list.add(factoryOrder);
        }
        return list;
    }


    @Override
    public boolean updateOrderOp(Order order, String[] arrays) {
        if (arrays.length > 0) {
            orderMapper.updateOrderByOp(order.getOrderSn(), Arrays.asList(arrays));
            return true;
        }
        return false;
    }



    @Override
    public boolean orderEnded(String orderSn) {
        //缺货记录mode设为3,使其消失
        //mode 为3 表示状态为终结订单
        //欠款金额进入供应商余额
        erpOweGoodsItemMapper.changeOrderSn(orderSn);
        return orderMapper.orderEnded(orderSn);
    }

    @Override
    public boolean warehouseDelivery(String orderSn) {
        return orderMapper.updateOrderItemIsNopur(orderSn, 1);
    }


    @Override
    public String orderStatus(String orderSn){
        Order order = orderMapper.selectByOrderSn(orderSn);
        if(order == null){
            return "无此订单!";
        }
        if(order.getStatus() == OrderStatus.ended.getStatus() ){
            return String.valueOf(OrderStatus.ended.getStatus());
        }
        int orderNum = Optional.ofNullable(orderItemMapper.selectOriginOrderNumber(orderSn)).orElse(0);
        int orderNumEd = Optional.ofNullable(orderItemMapper.selectOrderOutNumber(orderSn)).orElse(0);
        logger.info("原始订单数量{}, 出库订单数量{}", orderNum, orderNumEd);

        if(orderNumEd == 0){
            return String.valueOf(OrderStatus.notSold.getStatus());
        }else if(orderNum <= orderNumEd){
            return String.valueOf(OrderStatus.completed.getStatus());
        }else{
            return String.valueOf(OrderStatus.partialSales.getStatus());
        }

    }

    @Override
    @Transactional
    public void submitOrders(List<Integer> ids, AdminUser user){

        UserAddress userAddress =  userAddressMapper.selectOneByUserId(user.getUserId());
        if(userAddress == null){
            throw new RuntimeException("用户没有默认地址");
        }
        List<CartItem> cartItems = cartItemMapper.selectBatchIds(ids);
        if(cartItems.isEmpty()){
            throw new RuntimeException("没有选中商品!");
        }
        logger.info("购物车: {}", cartItems.size());
        final Map<String, List<CartItem>> result = new HashMap<>();
        cartItems.forEach((x)->{
            String supplierName =  supplierMapper.selectSupplierNameByGoodsId(x.getGoodsId());
            List<CartItem> objects = result.get(supplierName);
            if(objects == null){
                objects = new ArrayList<>();
                objects.add(x);
                result.put(supplierName, objects);
            }else{
                objects.add(x);
            }
        });

        Set<String> supplierNames = result.keySet();
        List<Order> orders = new ArrayList<>();
        String orderSn = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        int index = 1;
        logger.info("供应商名称: {}", supplierNames);
        for(String key : supplierNames){
            String nOrderSn = orderSn + "-" + index;
            index ++;
            List<CartItem> objs = result.get(key);
            //更具供应商生成对应订单
            BigDecimal total = BigDecimal.ZERO;
            for(CartItem object : objs){
                ErpGoods goods = goodMapper.selectById(object.getGoodsId());
                OrderItem item = new OrderItem();
                item.setOrderSn(nOrderSn);
                item.setBrandName(brandMapper.selectBrandNameByGoodsId(goods.getGoodsId()));
                item.setGoodsName(object.getGoodsName());
                item.setGoodsDesc(object.getGoodsDesc());
                item.setCartsId(goods.getCatId());
                item.setShopPrice(object.getShopPrice());
                item.setSuppliersId(goods.getSuppliersId());
                item.setSupplierName(key);
                item.setGoodsNum(object.getGoodsNum());
                orderItemMapper.insert(item);
                total = total.add(item.getShopPrice().multiply(BigDecimal.valueOf(item.getGoodsNum())));
                cartItemMapper.deleteById(object.getId());
            }
            Order order = new Order();
            order.setUserId(user.getUserId());
            //LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))
            //用户的默认地址

            order.setCreateTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
            order.setOrderSn(nOrderSn);
            order.setAddressValue(userAddress.getAddress());
            order.setAddressId(String.valueOf(userAddress.getAddressId()));
            order.setTotalMoney(total.doubleValue());
            order.setSupplierName(key);
            order.setReceipt(0);
            order.setRefund(0);
            order.setIsPay(1);
            order.setCartItems(objs);
            orderMapper.insert(order);
            orders.add(order);
        }

        String json = JSONArray.toJSONString(orders);

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("json", json);
        requestBody.add("userName", user.getUserName());
        logger.info("请求的数据: {}" , requestBody);
        RestTemplate restTemplate = new RestTemplate();
        Result response =
                restTemplate.postForObject(remoteUrl + "/order/remote-submit", requestBody, Result.class);
        if(response.getCode() != 200){
            throw new RuntimeException(response.getMsg());
        }
    }

    @Override
    public void submitOrderNew(List<CartItem> cartItems, AdminUser user) {
        UserAddress userAddress =  userAddressMapper.selectOneByUserId(user.getUserId());
        if(userAddress == null){
            throw new RuntimeException("用户没有默认地址");
        }
        if(cartItems.isEmpty()){
            throw new RuntimeException("没有选中商品!");
        }
        logger.info("购物车: {}", cartItems.size());
        final Map<String, List<CartItem>> result = new HashMap<>();
        cartItems.forEach((x)->{
            String supplierName =  supplierMapper.selectSupplierNameByGoodsId(x.getGoodsId());
            List<CartItem> objects = result.get(supplierName);
            if(objects == null){
                objects = new ArrayList<>();
                objects.add(x);
                result.put(supplierName, objects);
            }else{
                objects.add(x);
            }
        });

        Set<String> supplierNames = result.keySet();
        List<Order> orders = new ArrayList<>();
        String orderSn = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        int index = 1;
        logger.info("供应商名称: {}", supplierNames);
        for(String key : supplierNames){
            String nOrderSn = orderSn + "-" + index;
            index ++;
            List<CartItem> objs = result.get(key);
            //更具供应商生成对应订单
            BigDecimal total = BigDecimal.ZERO;
            for(CartItem object : objs){
                ErpGoods goods = goodMapper.selectById(object.getGoodsId());
                OrderItem item = new OrderItem();
                item.setOrderSn(nOrderSn);
                item.setBrandName(brandMapper.selectBrandNameByGoodsId(goods.getGoodsId()));
                item.setGoodsName(object.getGoodsName());
                item.setGoodsDesc(object.getGoodsDesc());
                item.setCartsId(goods.getCatId());
                item.setShopPrice(object.getShopPrice());
                item.setSuppliersId(goods.getSuppliersId());
                item.setSupplierName(key);
                item.setGoodsNum(object.getGoodsNum());
                orderItemMapper.insert(item);
                total = total.add(item.getShopPrice().multiply(BigDecimal.valueOf(item.getGoodsNum())));
                cartItemMapper.deleteById(object.getId());
            }
            Order order = new Order();
            order.setUserId(user.getUserId());
            //LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))
            //用户的默认地址

            order.setCreateTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
            order.setOrderSn(nOrderSn);
            order.setAddressValue(userAddress.getAddress());
            order.setAddressId(String.valueOf(userAddress.getAddressId()));
            order.setTotalMoney(total.doubleValue());
            order.setSupplierName(key);
            order.setReceipt(0);
            order.setRefund(0);
            order.setIsPay(1);
            order.setCartItems(objs);
            orderMapper.insert(order);
            orders.add(order);
        }

        String json = JSONArray.toJSONString(orders);

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("json", json);
        requestBody.add("userName", user.getUserName());
        logger.info("请求的数据: {}" , requestBody);
        RestTemplate restTemplate = new RestTemplate();
        Result response =
                restTemplate.postForObject(remoteUrl + "/order/remote-submit", requestBody, Result.class);
        if(response.getCode() != 200){
            throw new RuntimeException(response.getMsg());
        }
    }
}
